package com.sleep.psy.external_server.business.main.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sleep.psy.external_server.business.main.entity.MainScheme;
import com.sleep.psy.external_server.business.main.entity.MainUserScheme;
import com.sleep.psy.external_server.business.main.entity.dto.SchemeInfo;
import com.sleep.psy.external_server.business.main.entity.dto.Training;
import com.sleep.psy.external_server.business.main.entity.vo.GetSchemeReq;
import com.sleep.psy.external_server.business.main.mapper.MainUserSchemeMapper;
import com.sleep.psy.external_server.business.main.service.MainSchemeService;
import com.sleep.psy.external_server.business.main.service.MainUserSchemeService;
import com.sleep.psy.external_server.business.psy.entity.PsyBaseVideo;
import com.sleep.psy.external_server.business.psy.service.PsyBaseVideoService;
import com.sleep.psy.external_server.business.resourse.entity.ResourseScale;
import com.sleep.psy.external_server.business.resourse.mapper.ResourseScaleMapper;
import com.sleep.psy.external_server.business.resourse.service.ResourseScaleService;
import com.sleep.psy.external_server.constants.MySqlConstant;
import com.sleep.psy.external_server.result.Result;
import com.sleep.psy.external_server.result.ResultEnum;
import com.sleep.psy.external_server.result.ResultUtil;
import com.sleep.psy.external_server.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 用户方案表 服务实现类
 * </p>
 *
 * @author wenliguo
 * @since 2025-08-12
 */
@Service
public class MainUserSchemeServiceImpl extends ServiceImpl<MainUserSchemeMapper, MainUserScheme> implements MainUserSchemeService {

    protected Logger logger = LoggerFactory.getLogger(MainUserSchemeService.class);

    @Autowired
    private MainUserSchemeMapper mainUserSchemeMapper;

    @Autowired
    private MainSchemeService mainSchemeService;

    @Autowired
    private PsyBaseVideoService baseVideoService;

    @Autowired
    private ResourseScaleMapper resourseScaleMapper;


    /**
     * 新增用户方案
     * @author wenliguo
     * @date 2025/8/13 10:04
     * @param userScheme 用户方案
     */
    @Override
    public void addScheme(MainUserScheme userScheme) {
        mainUserSchemeMapper.insert(userScheme);
    }

    /**
     * 通过用户id和方案id获取量表、音频、视频
     * @author wenliguo
     * @date 2025/8/19 13:39
     * @param req 请求
     * @return com.sleep.psy.external_server.result.Result
     */
    @Override
    public Result selectUserScheme(GetSchemeReq req) {

        QueryWrapper<MainUserScheme> wrapper = new QueryWrapper<>();
//        wrapper.eq("main_scheme_id", req.getSchemeId())
//                .like("main_user_ids", req.getUserId())
//                .eq("is_del", MySqlConstant.IS_DEL_0)
//                .eq("status", MySqlConstant.STATUS_1);

        wrapper.like("main_user_ids", req.getUserId())
                .eq("is_del", MySqlConstant.IS_DEL_0)
                .eq("status", MySqlConstant.STATUS_1)
                .orderByDesc("update_time");

        List<MainUserScheme> schemes = mainUserSchemeMapper.selectList(wrapper);
        Date date = new Date();
        if (schemes.isEmpty()) {
            MainScheme mainScheme = mainSchemeService.selectById(req.getSchemeId());
            if (null == mainScheme) {
                return ResultUtil.error(ResultEnum.NO_SCHEME);
            }

            String info = mainScheme.getSchemeInfo();
            SchemeInfo schemeInfo = JSONObject.parseObject(info, SchemeInfo.class);

            Integer status = schemeInfo.getStatus();
            if (MySqlConstant.STATUS_0.equals(status)) {
                return ResultUtil.error(ResultEnum.SCHEME_STATUS_0);
            }

            String endDate = schemeInfo.getEndDate();
            if (null != endDate) {
                Date eDate = DateUtils.stringToDate(endDate, DateUtils.DATE_FORMAT);//9.30
                if (eDate.before(date)) {
                    return ResultUtil.error(ResultEnum.NO_END_DATE);
                }
            }

            MainUserScheme userScheme = new MainUserScheme();
            userScheme.setMainSchemeId(req.getSchemeId());
            if (null != schemeInfo.getStartDate()) {
                userScheme.setSendStartTime(schemeInfo.getStartDate());
            }
            if (null != schemeInfo.getEndDate()) {
                userScheme.setSendEndTime(schemeInfo.getEndDate());
            }

            schemeInfo.getTraining().setSleepControl(null);
            userScheme.setSchemeInfo(JSON.toJSONString(schemeInfo, SerializerFeature.WriteMapNullValue));
            userScheme.setMainUserIds(req.getUserId() + "");
            this.addScheme(userScheme);

            String startDate = schemeInfo.getStartDate();
            if (null != startDate) {
                Date sDate = DateUtils.stringToDate(startDate, DateUtils.DATE_FORMAT);
                if (sDate.after(date)) {
                    return ResultUtil.error(ResultEnum.NO_START_DATE);
                }
            }

            HashMap<String, Object> map = mainSchemeService.selectInfoById(req.getSchemeId());
            return ResultUtil.success(map);
        }

        String schemeInfo = schemes.get(0).getSchemeInfo();
        SchemeInfo info = JSONObject.parseObject(schemeInfo,SchemeInfo.class);

        Integer status = info.getStatus();
        if (MySqlConstant.STATUS_0.equals(status)) {
            return ResultUtil.error(ResultEnum.SCHEME_STATUS_0);
        }
        String startDate = info.getStartDate();
        if (null != startDate) {
            Date sDate = DateUtils.stringToDate(startDate, DateUtils.DATE_FORMAT);
            if (sDate.after(date)) {
                return ResultUtil.error(ResultEnum.NO_START_DATE);
            }
        }

        String advice = info.getAdvice();
        String scaleIds = info.getEvaluation();
        Training training = info.getTraining();
        String videoIds = training.getSleepTraining();
        String audioIds = training.getMoodDepress();
        String sleepHeath = training.getSleepHeath();
        String sleepControl = training.getSleepControl();

        //String videoIds = mainScheme.getTraining().getSleepTraining();
//        String audioIds = mainScheme.getTraining().getMoodDepress();
//        String scaleIds = mainScheme.getEvaluation();
//        String advice = mainScheme.getAdvice();
//        String sleepHeath = mainScheme.getTraining().getSleepHeath();
//        String sleepControl = mainScheme.getTraining().getSleepControl();


//        Integer status = mainScheme.getStatus();
//        if (MySqlConstant.STATUS_0.equals(status)) {
//            return ResultUtil.error(ResultEnum.SCHEME_STATUS_0);
//        }
//
//        String startDate = mainScheme.getStartDate();
//        if (null != startDate) {
//            Date sDate = DateUtils.stringToDate(startDate, DateUtils.DATE_FORMAT);
//            if (sDate.after(date)) {
//                return ResultUtil.error(ResultEnum.NO_START_DATE);
//            }
//        }
//
//        String videoIds = mainScheme.getTraining().getSleepTraining();
//        String audioIds = mainScheme.getTraining().getMoodDepress();
//        String scaleIds = mainScheme.getEvaluation();
//        String advice = mainScheme.getAdvice();
//        String sleepHeath = mainScheme.getTraining().getSleepHeath();
//        String sleepControl = mainScheme.getTraining().getSleepControl();


        HashMap<String, Object> map = new HashMap<>();
        map.put("scaleList", new ArrayList<>());
        map.put("audioList", new ArrayList<>());
        map.put("videoList", new ArrayList<>());
        map.put("sleepHeathVideoList", new ArrayList<>());
        map.put("advice", advice);
        map.put("sleepControl", sleepControl);

        //睡眠卫生
        ArrayList<PsyBaseVideo> sleepHeathVideoSet = new ArrayList<>();
        if (StringUtils.isNotBlank(sleepHeath)) {
            if (sleepHeath.contains(",")) {
                String[] split = sleepHeath.split(",");
                for (String s : split) {
                    PsyBaseVideo video = baseVideoService.selectById(Integer.parseInt(s));
                    if (null != video) {
                        sleepHeathVideoSet.add(video);
                    }
                }
            } else {
                PsyBaseVideo video = baseVideoService.selectById(Integer.parseInt(sleepHeath));
                if (null != video) {
                    sleepHeathVideoSet.add(video);
                }
            }
            map.put("sleepHeathVideoList",sleepHeathVideoSet);
        }


        //视频
        ArrayList<PsyBaseVideo> baseVideos = new ArrayList<>();
        if (StringUtils.isNotBlank(videoIds)) {
            if (videoIds.contains(",")) {
                String[] split = videoIds.split(",");
                for (String s : split) {
                    PsyBaseVideo video = baseVideoService.selectById(Integer.parseInt(s));
                    if (null != video) {
                        baseVideos.add(video);
                    }
                }
            } else {
                PsyBaseVideo video = baseVideoService.selectById(Integer.parseInt(videoIds));
                if (null != video) {
                    baseVideos.add(video);
                }
            }
            map.put("videoList", baseVideos);
        }

        //音频
        ArrayList<PsyBaseVideo> videos = new ArrayList<>();
        if (StringUtils.isNotBlank(audioIds)) {
            if (audioIds.contains(",")) {
                String[] split = audioIds.split(",");
                for (String s : split) {
                    PsyBaseVideo video = baseVideoService.selectById(Integer.parseInt(s));
                    if (null != video) {
                        videos.add(video);
                    }
                }
            } else {
                PsyBaseVideo video = baseVideoService.selectById(Integer.parseInt(audioIds));
                if (null != video) {
                    videos.add(video);
                }
            }

            map.put("audioList", videos);
        }

        //量表
        ArrayList<ResourseScale> scales = new ArrayList<>();
        if (StringUtils.isNotBlank(scaleIds)) {
            if (scaleIds.contains(",")) {

                String[] split = scaleIds.split(",");
                for (String s : split) {
                    ResourseScale scale = resourseScaleMapper.selectById(Integer.parseInt(s));
                    if (null != scale) {
                        scales.add(scale);
                    }
                }

            } else {
                ResourseScale scale = resourseScaleMapper.selectById(Integer.parseInt(scaleIds));
                if (null != scale) {
                    scales.add(scale);
                }
            }
            map.put("scaleList", scales);
        }
        return ResultUtil.success(map);
    }

    /**
     * 通过方案id和用户id获取用户的方案
     * @author wenliguo
     * @date 2025/8/26 14:10
     * @param schemeId 方案id
     * @param userId 用户id
     * @return java.util.List<com.sleep.psy.external_server.business.main.entity.MainUserScheme>
     */
    @Override
    public List<MainUserScheme> selectByUserIdAndSchemeId(Integer schemeId, Long userId) {
        QueryWrapper<MainUserScheme> wrapper = new QueryWrapper<>();
        wrapper.eq("main_scheme_id", schemeId)
                .like("main_user_ids", userId)
                .eq("is_del", MySqlConstant.IS_DEL_0)
                .eq("status", MySqlConstant.STATUS_1);

        return mainUserSchemeMapper.selectList(wrapper);
    }
}
